package com.atguigu.netty.group.chat.client;

import com.alibaba.fastjson.JSON;
import com.atguigu.netty.group.chat.model.MsgDTO;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatClientHandler extends ChannelInboundHandlerAdapter {

    private String userName;

    public ChatClientHandler(String userName) {
        this.userName = userName;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String msg = "大家好，我是" + userName;
        String jsonMsg = JSON.toJSONString(new MsgDTO(userName, msg));
        ctx.writeAndFlush(Unpooled.copiedBuffer(jsonMsg, CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        String serverMsg = buf.toString(CharsetUtil.UTF_8);
        System.out.println(serverMsg);
    }
}
